package com.example.kotlincustomview.view

import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.RectF
import android.graphics.drawable.Drawable
import android.util.AttributeSet
import android.view.View
import android.widget.ImageView
import com.example.kotlincustomview.R

class CircleImage2View : ImageView {

    private var mWidth: Int = 0
    private var mCirclePaint: Paint? = null
    private val mRectF = RectF() //背景圆

    constructor(context: Context?) : super(context) {
        initData()
    }

    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) {
        initData()
    }

    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
        initData()
    }

    private fun initData() {
        mCirclePaint = Paint()
        mCirclePaint?.style = Paint.Style.FILL
        mCirclePaint?.color = resources.getColor(R.color.color_ffc7ab)//默认蓝色
        mCirclePaint?.isAntiAlias = true
    }

    override fun onDraw(canvas: Canvas?) {
        mRectF.set(0f, 0f, mWidth.toFloat(), mWidth.toFloat())
        canvas?.drawArc(mRectF, 0f, 365f, false, mCirclePaint!!)
        super.onDraw(canvas)
    }

    /**
     * 设置颜色
     * */
    fun setPaintBackground(background: Int) {
        mCirclePaint?.color = resources.getColor(background)
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        var height = View.getDefaultSize(suggestedMinimumHeight, heightMeasureSpec)
        mWidth = View.getDefaultSize(suggestedMinimumWidth, widthMeasureSpec)
        var min = Math.min(mWidth, height)// 获取View最短边的长度
        setMeasuredDimension(min, min)// 强制改View为以最短边为长度的正方形
    }

}